package com.example.cyh.bczapp.Code.Activity;

import android.app.Activity;
import android.os.Bundle;
import android.os.Looper;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.example.cyh.bczapp.Code.BLL.PlanBLL;
import com.example.cyh.bczapp.Code.BLL.UserBLL;
import com.example.cyh.bczapp.Code.BLL.WordGroupBLL;
import com.example.cyh.bczapp.Code.Controll.WheelView;
import com.example.cyh.bczapp.Code.Model.PlanInfEntity;
import com.example.cyh.bczapp.Code.Model.UserInfEntity;
import com.example.cyh.bczapp.Code.Model.WordGroupInfEntity;
import com.example.cyh.bczapp.R;


import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;


public class ChangePlan extends Activity implements View.OnClickListener {
    private UserInfEntity user;

    //下拉菜单相关数据
    private Spinner spinner;
    private List<WordGroupInfEntity> data_list;
    private ArrayAdapter<String> arr_adapter;
    //滑动选择器
    private WheelView wv_day;
    private WheelView wv_word;
    //全部数据
    private Map<WordGroupInfEntity, Map<String, String>> name_word_day;
    //可选单词数
    private static final List<String> words = new ArrayList<String>();
    //当前显示的天数
    private List<String> days = new ArrayList<String>();
    private LinearLayout wg;
    //计划名控件
    private TextView wgname1;
    private TextView wgname2;
    private TextView wgname3;
    private TextView wgname4;
    private RelativeLayout Selectwg = null;
    private ArrayList<RelativeLayout> wglist;
    private ArrayList<PlanInfEntity> listp = new ArrayList<PlanInfEntity>();
    private View.OnClickListener bt_addonclicklistener;
    private View.OnClickListener bt_alertonclicklistener;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_change_plan);
        wg = (LinearLayout) findViewById(R.id.wgplanall);
        wgname1 = (TextView) findViewById(R.id.wgname1);
        wgname2 = (TextView) findViewById(R.id.wgname2);
        wgname3 = (TextView) findViewById(R.id.wgname3);
        wgname4 = (TextView) findViewById(R.id.wgname4);
        user = (UserInfEntity) getIntent().getSerializableExtra("user");
        bt_addonclicklistener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        PlanInfEntity rd = Getarecordfromui(null);
                        PlanBLL lb = new PlanBLL();
                        try {
                            UserBLL ub = new UserBLL();
                            ub.AddPlanId(lb.AddPlan(rd), user.U_Id);
                            Looper.prepare();
                            Toast.makeText(ChangePlan.this, "添加成功", Toast.LENGTH_SHORT).show();
                            if(listp==null)
                                listp=new ArrayList<PlanInfEntity>();
                            listp.add(rd);
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    if(listp.size()==1)
                                    {
                                        wg.removeAllViews();
                                    }
                                   View addview= wglist.get(listp.size() - 1);
                                    addview.setVisibility(View.VISIBLE);
                                    wg.addView(addview);
                                    Loaddate();
                                    Setwgpic(listp);
                                }
                            });
                            Looper.loop();
                        } catch (Exception e) {
                            Toast.makeText(ChangePlan.this, "添加失败", Toast.LENGTH_SHORT).show();
                        }
                    }
                }).start();

            }
        };
        bt_alertonclicklistener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        if (Selectwg == null)
                            return;
                        PlanInfEntity rd = Getarecordfromui((PlanInfEntity) Selectwg.getTag());
                        PlanBLL lb = new PlanBLL();
                        Looper.prepare();
                        try {
                            if (lb.AlertPlan(rd).equals("true")) {
                                listp.remove((PlanInfEntity) Selectwg.getTag());
                                listp.add(rd);
                                ClearwgSelect();
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        try {
                                            ClearwgSelect();
                                            ((Button) findViewById(R.id.bt_planadd)).setText("添加");
                                            ((Button) findViewById(R.id.bt_planadd)).setOnClickListener(bt_addonclicklistener);
                                        } catch (Exception ex) {
                                            Toast.makeText(ChangePlan.this, ex.getMessage(), Toast.LENGTH_SHORT).show();
                                        }
                                    }
                                });
                                Toast.makeText(ChangePlan.this, "修改成功", Toast.LENGTH_SHORT).
                                        show();

                            } else {
                                Toast.makeText(ChangePlan.this, "修改失败", Toast.LENGTH_SHORT).
                                        show();
                            }
                        } catch (Exception e) {
                            Toast.makeText(ChangePlan.this, "修改失败", Toast.LENGTH_SHORT).
                                    show();
                        } finally {
                            Looper.loop();
                        }
                    }
                }).start();
            }
        };
        //返回按钮
        ((Button) findViewById(R.id.bt_changeplanback)).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        //添加监听事件
        Button add = (Button) findViewById(R.id.bt_planadd);
        ((TextView) findViewById(R.id.tv_changeplandelet)).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (Selectwg == null) {
                    Toast.makeText(ChangePlan.this, "请先选择一个计划!", Toast.LENGTH_SHORT).show();
                    return;
                }
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        PlanBLL pb = new PlanBLL();
                        try {
                            Looper.prepare();
                            if (pb.DeletPlan(((PlanInfEntity) Selectwg.getTag()).P_Id).equals("true")) {
                                UserBLL ub = new UserBLL();
                                if(((PlanInfEntity) Selectwg.getTag()).P_Id==user.U_PlanId)
                                    ub.SetPlanEmpty(String.valueOf(user.U_Id));
                                runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        wg.removeView(Selectwg);
                                    }
                                });

                                listp.remove((PlanInfEntity) Selectwg.getTag());
                                if (((PlanInfEntity) Selectwg.getTag()).P_IsRead == "true")
                                    ub.AddPlanId("", ((PlanInfEntity) Selectwg.getTag()).U_Id);
                                Toast.makeText(ChangePlan.this, "删除成功", Toast.LENGTH_SHORT).show();
                            } else
                                Toast.makeText(ChangePlan.this, "删除失败", Toast.LENGTH_SHORT).
                                        show();
                        } catch (Exception e) {
                            Toast.makeText(ChangePlan.this, "删除失败", Toast.LENGTH_SHORT).
                                    show();
                        } finally {
                            Looper.loop();
                        }
                    }
                }).start();
            }
        });
        //添加计划
        add.setOnClickListener(bt_addonclicklistener);
        View.OnLongClickListener selectwg = new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                try {
                    ClearwgSelect();
                    v.setBackgroundResource(R.drawable.test);
                    Selectwg = (RelativeLayout) v;
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            PlanInfEntity planinf = (PlanInfEntity) Selectwg.getTag();
                            //改变下拉框
                            for (int i = 0; i < arr_adapter.getCount(); i++) {
                                if (arr_adapter.getItem(i) == WgidGetName(planinf.WG_id))
                                    spinner.setSelection(i);
                            }
                            //改button  和文字为修改
                            ((Button) findViewById(R.id.bt_planadd)).setText("修改");
                            ((TextView) findViewById(R.id.tv_operation)).setText("修改计划");
                            ((Button) findViewById(R.id.bt_planadd)).setOnClickListener(bt_alertonclicklistener);
                        }
                    });
                } catch (Exception ex) {
                    Toast.makeText(ChangePlan.this, ex.getMessage(), Toast.LENGTH_SHORT).show();
                }
                return false;
            }
        };
        RelativeLayout wg1 = (RelativeLayout) findViewById(R.id.wgplan1);
        RelativeLayout wg2 = (RelativeLayout) findViewById(R.id.wgplan2);
        RelativeLayout wg3 = (RelativeLayout) findViewById(R.id.wgplan3);
        RelativeLayout wg4 = (RelativeLayout) findViewById(R.id.wgplan4);
        wglist = new ArrayList<RelativeLayout>();
        wglist.add(wg1);
        wglist.add(wg2);
        wglist.add(wg3);
        wglist.add(wg4);
        wg1.setOnLongClickListener(selectwg);
        wg2.setOnLongClickListener(selectwg);
        wg3.setOnLongClickListener(selectwg);
        wg4.setOnLongClickListener(selectwg);
        findViewById(R.id.changeplanview).setOnClickListener(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        Loaddate();
    }

    @Override
    public void onClick(View v) {
        if (Selectwg == null) {
            return;
        }
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                try {
                    ClearwgSelect();
                    ((Button) findViewById(R.id.bt_planadd)).setText("添加");
                    ((Button) findViewById(R.id.bt_planadd)).setOnClickListener(bt_addonclicklistener);
                } catch (Exception ex) {
                    Toast.makeText(ChangePlan.this, ex.getMessage(), Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    //加载下拉菜单数据
    private void Loadwgname() {
        WordGroupBLL wordGroupBLL = new WordGroupBLL();
        //数据
        data_list = wordGroupBLL.GetAllwgName();
        spinner = (Spinner) findViewById(R.id.sp_wgname);
        //适配器
        arr_adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item);
        //写入数据
        for (WordGroupInfEntity wg : data_list
                ) {
            arr_adapter.add(wg.WG_Name);
        }
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        LoadWva(true);
                    }
                });
                //Toast.makeText(ChangePlan.this, arr_adapter.getItem(position).toString(), Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                //设置样式
                arr_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                spinner.setSelection(0);
                //加载适配器
                spinner.setAdapter(arr_adapter);
            }
        });
    }

    //加载滑动选择控件
    private void LoadWva(boolean changewg) {
        //wv_day.removeAllViews();
        if (!changewg) {
            //设置可选的单词数
            for (int i = 5; i <= 30; i += 5) {
                words.add(String.valueOf(i) + "个单词");
            }
            //写入界面
            wv_word.setItems(words);
            wv_word.setOnWheelViewListener(new WheelView.OnWheelViewListener() {
                @Override
                public void onSelected(int selectedIndex, String item) {
                    ChangeWheelView(item, false);
                }
            });
        }
        //制作字典
        name_word_day = new HashMap<WordGroupInfEntity, Map<String, String>>();
        Set<WordGroupInfEntity> name = name_word_day.keySet();
        //添加第一个键 词组类
        for (WordGroupInfEntity n : data_list
                ) {
            name_word_day.put(n, null);
        }
        //添加value
        for (WordGroupInfEntity n : name
                ) {
            Map<String, String> values = new HashMap<String, String>();
            for (String number : words
                    ) {
                int word_number = Integer.parseInt(number.replace("个单词", ""));
                int day_number = n.WG_Count / word_number;
                if (n.WG_Count % word_number != 0)
                    day_number++;
                values.put(String.valueOf(word_number), String.valueOf(day_number));
            }
            name_word_day.put(n, values);
        }
        //在字典中提取当前选中项的天数数据集合
        Set<WordGroupInfEntity> key = name_word_day.keySet();
        String selectname = spinner.getSelectedItem().toString();
        days = new ArrayList<String>();
        for (WordGroupInfEntity wg : key
                ) {
            if (wg.WG_Name == selectname) {
                for (String n : words
                        ) {
                    String nb = name_word_day.get(wg).get(n.replace("个单词", ""));
                    if (!days.contains(nb) && !nb.equals(""))
                        days.add(nb);
                }
            }
        }
        wv_day = (WheelView) findViewById(R.id.wv_planinfdaynumber);
        wv_day.setItems(days);
        wv_day.setOnWheelViewListener(new WheelView.OnWheelViewListener() {
            @Override
            public void onSelected(int selectedIndex, String item) {
                ChangeWheelView(item, true);
            }
        });
    }

    //动态改变滑动选择器
    private void ChangeWheelView(String item, boolean day) {
        if (item.equals(""))
            return;
        if (day) {
            for (WordGroupInfEntity wg : data_list
                    ) {
                if (wg.WG_Name == spinner.getSelectedItem().toString()) {
                    Map<String, String> dic = name_word_day.get(wg);
                    for (String key : dic.keySet()
                            ) {
                        if (dic.get(key) == item) {
                            int index = words.indexOf(key + "个单词");
                            wv_word.setSeletion(index);
                        }
                    }
                }
            }
        } else {
            for (WordGroupInfEntity wg : data_list
                    ) {
                if (wg.WG_Name == spinner.getSelectedItem().toString()) {
                    Map<String, String> dic = name_word_day.get(wg);
                    for (String key : dic.keySet()
                            ) {
                        if (key.equals(item.replace("个单词", ""))) {
                            wv_day.setSeletion(days.indexOf(dic.get(key)));
                        }
                    }
                }
            }
        }


    }

    private void Setwgpic(ArrayList<PlanInfEntity> wginf) {
        if(wginf==null) {
            findViewById(R.id.wgplan1).setVisibility(View.INVISIBLE);
            findViewById(R.id.wgplan2).setVisibility(View.INVISIBLE);
            findViewById(R.id.wgplan3).setVisibility(View.INVISIBLE);
            findViewById(R.id.wgplan4).setVisibility(View.INVISIBLE);
            return;
        }
        int size = wginf.size();
        if (size <= 0)
            return;
        if (size < 4) {
            switch (size) {
                case 1:
                    wg.removeView(findViewById(R.id.wgplan4));
                    wg.removeView(findViewById(R.id.wgplan3));
                    wg.removeView(findViewById(R.id.wgplan2));
                    break;
                case 2:
                    wg.removeView(findViewById(R.id.wgplan4));
                    wg.removeView(findViewById(R.id.wgplan3));
                    break;
                case 3:
                    wg.removeView(findViewById(R.id.wgplan4));
                    break;
                default:
                    break;
            }
        }
        for (int i = 0; i < listp.size(); i++) {
            switch (i + 1) {
                case 1:
                    wgname1.setText(WgidGetName(listp.get(i).WG_id));
                    findViewById(R.id.wgplan1).setTag(listp.get(i));
                    break;
                case 2:
                    wgname2.setText(WgidGetName(listp.get(i).WG_id));
                    findViewById(R.id.wgplan2).setTag(listp.get(i));
                    break;
                case 3:
                    wgname3.setText(WgidGetName(listp.get(i).WG_id));
                    findViewById(R.id.wgplan3).setTag(listp.get(i));
                    break;
                case 4:
                    wgname4.setText(WgidGetName(listp.get(i).WG_id));
                    findViewById(R.id.wgplan4).setTag(listp.get(i));
                    break;
                default:
                    break;
            }
        }

    }

    private String WgidGetName(int wg_id) {
        for (WordGroupInfEntity wg : data_list
                ) {
            if (wg.WG_Id == wg_id)
                return wg.WG_Name;
        }
        return "";
    }

    private void ClearwgSelect() {
        Selectwg = null;
        try {
            findViewById(R.id.wgplan1).setBackgroundResource(R.drawable.blank);
            findViewById(R.id.wgplan2).setBackgroundResource(R.drawable.blank);
            findViewById(R.id.wgplan3).setBackgroundResource(R.drawable.blank);
            findViewById(R.id.wgplan4).setBackgroundResource(R.drawable.blank);
        } catch (Exception ex) {

        }
    }

    private PlanInfEntity Getarecordfromui(PlanInfEntity rd) {
        if (rd == null)
            rd = new PlanInfEntity();
        rd.P_DayWork = wv_word.getSeletedItem().replace("个单词", "");
        rd.P_OverDay = wv_day.getSeletedItem();
        rd.P_ReviewList = "";
        Date date = new Date();
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = format.format(date);
        rd.P_StarTime = time;
        rd.U_Id = user.U_Id;
        rd.P_IsRead = "true";
        for (WordGroupInfEntity wg : data_list
                ) {
            if (wg.WG_Name.equals(spinner.getSelectedItem()))
                rd.WG_id = wg.WG_Id;
        }
        return rd;
    }

    private void Loaddate() {
        //加载控件数据
        new Thread(new Runnable() {
            @Override
            public void run() {
                //加载下拉菜单数据
                Loadwgname();
                UserBLL ub = new UserBLL();
                listp = ub.GetAllPlan(user.U_Id);
                //滑动选择器
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        wv_word = (WheelView) findViewById(R.id.wv_planinfwordnumber);
                        wv_day = (WheelView) findViewById(R.id.wv_planinfdaynumber);
                        LoadWva(false);
                        Setwgpic(listp);
                    }
                });

            }
        }).start();

    }
}
